#!/bin/bash

EXECFILE="/home/mythtv/new_mythbox_link/MythBoxLink.py"
#logFile="/var/log/mythboxlink.log"
logFile="/dev/stdout"

function killtree {
  for pid in "$@"; do
    childpids=$(ps --ppid "$pid" -o pid | tail -n +2 | tr '\n' ' ')
    numchildren=$(echo "$childpids" | wc -w)

    if [ $numchildren -gt 0 ]; then
      killtree $childpids
    fi

    kill -9 "$pid"
  done
}

function checkpid {
  ps --pid "$1" -o pid | tail -n +2 | tr '\n' ' ' | wc -w
}

if [ -e /var/run/mythboxlink.pid ]; then
  pid=$(cat /var/run/mythboxlink.pid | tr -d '\n')
  if [ $(checkpid "$pid") -gt 0 ]; then
    #echo "ERROR: MythBoxLink is already running (PID: $pid)" >> "$logFile"
    #exit 1
    killtree "$pid"
    sleep 3s
  else
    echo "Warning: removing stale pid file." >> "$logFile"
    rm -f /var/run/mythboxlink.pid
  fi
fi

su -c "$EXECFILE" mythtv > "$logFile" 2>&1 &
echo "$!" > /var/run/mythboxlink.pid
pid=$(cat /var/run/mythboxlink.pid | tr -d '\n')
echo "CRON: Started MythBoxLink (PID $pid) on $(date)" >> "$logFile"
# 50 minute time limit
timeLimit=3000
runningTime=0

while [ /bin/true ]; do
  sleep 1s
  ((++runningTime))

  if [ $runningTime -gt $timeLimit ]; then
    echo "ERROR: MythBoxLink was running for WAY too long. Killed." >> "$logFile"
    exit 1
  fi

  if [ $(checkpid "$pid") -lt 1 ]; then
    rm /var/run/mythboxlink.pid
    exit 0
  fi
done
